package com.shenmazong.serveruserapi.task;

import com.shenmazong.TbNo;
import com.shenmazong.serveruserapi.service.TbNoService;
import com.shenmazong.utils.ConstUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 田不平
 * @project server-xing-00
 * @date 2020/8/14 11:49 AM
 * http://www.shenmazong.com
 */

@Component
@EnableScheduling
@Slf4j
public class UserNoTask {

    @Autowired
    private TbNoService tbNoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(fixedRate = 30000)
    public void userNoTask() {
        log.info("userNoTask ...");

        //--1 检查userno
        if(tbNoService.getFreeUserNoCount() > 100) {
            return;
        }

        //--2 生成userno
        Integer maxUserNo = tbNoService.getMaxUserNo();
        if(maxUserNo == 0) {
            maxUserNo = 100000;
        }

        for (int idx = 0; idx < 200; idx++) {

            tbNoService.addUserNo(maxUserNo+idx+1);
        }
    }

    @Scheduled(fixedRate = 30000)
    public void userNoTaskForRedis() {

        log.info("userNoTaskForRedis....");
        // 1 2 3 4 5 6
        // 1 2
        // 原方案：用list来模拟队列（有bug）
        // 新方案：用set来控制用户编码

        //--1 检查redis中用户的编码是否充足
        long size = redisTemplate.opsForSet().size(ConstUtils.QUEUE_USER_NO_NAME);
        if(size > 10) {
            return;
        }

        //--2 向redis加入空闲用户编码
        List<TbNo> freeUserNoList = tbNoService.getFreeUserNoList();
        for(TbNo no : freeUserNoList) {
            redisTemplate.opsForSet().add(ConstUtils.QUEUE_USER_NO_NAME, no.getUserno());
        }
    }
}
